package com.acme.concurrent.executor;

import java.io.File;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;

/**
 * @author Gregory Sobko
 */
class FileIndexer implements Runnable {
    private final BlockingQueue<File> queue;
    private final FileQueuePool fileQueuePool;
    private final ExecutorService executorService;
    private final int index;
    private int indexed = 0;
    private int stolen = 0;


    public FileIndexer(FileQueuePool fileQueuePool, int i, ExecutorService executorService) {
        queue = fileQueuePool.getQueue(i);
        this.fileQueuePool = fileQueuePool;
        index = i;
        this.executorService = executorService;
    }

    public void run() {
        try {
            File file = queue.poll();
            if(file == null){
                file = fileQueuePool.trySteal(index);
                if(file != null){
                    stolen++;
                }
            }
            if(file == null){
                file = queue.take();
            }
            if(file == FileQueuePool.POISONOUS_PILL){
                System.out.println("Indexer#" + index + " Indexed: " + indexed + " stolen: " + stolen);
                return;
            }
            indexFile(file);
            executorService.submit(this);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    public void indexFile(File file){
        indexed++;
    }
}

